package com.hty.filemanager;

import android.content.Intent;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class TexteditActivity extends AppCompatActivity {

    String path, filename;
    EditText editText, editText_search;
    TextView textView_search_index;
    ImageButton imageButton_search_prev, imageButton_search_next, imageButton_search_close;
    LinearLayout linearLayout_search;
    int index = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_textedit);
        android.support.v7.app.ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        Intent intent = getIntent();
        path = intent.getStringExtra("Path");
        filename = path.substring(path.lastIndexOf(File.separator) + 1);
        setTitle(filename);

        editText = findViewById(R.id.editText);
        editText.setBackgroundDrawable(null);
        editText.setText(ReadTextFile(path));
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                setTitle(filename + "*");
            }
        });

        linearLayout_search = findViewById(R.id.linearLayout_search);
        linearLayout_search.setVisibility(View.GONE);
        textView_search_index = findViewById(R.id.textView_search_index);
        editText_search = findViewById(R.id.editText_search);
        imageButton_search_prev = findViewById(R.id.imageButton_search_prev);
        imageButton_search_next = findViewById(R.id.imageButton_search_next);
        imageButton_search_close = findViewById(R.id.imageButton_search_close);
        imageButton_search_prev.setOnClickListener(new MyOnClickListener());
        imageButton_search_next.setOnClickListener(new MyOnClickListener());
        imageButton_search_close.setOnClickListener(new MyOnClickListener());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, 0, 0, "保存");
        menu.add(0, 1, 1, "查找");
        menu.add(0, 2, 2, "退出");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int item_id = item.getItemId();
        switch (item_id) {
            case 0:
                try {
                    String s = editText.getText().toString();
                    FileOutputStream FOS = new FileOutputStream(path);
                    FOS.write(s.getBytes());
                    FOS.flush();
                    FOS.close();
                    MediaScannerConnection.scanFile(TexteditActivity.this, new String[]{ path }, null, null);
                    setTitle(filename);
                } catch (Exception e) {
                    Toast.makeText(this, e.toString(), Toast.LENGTH_SHORT).show();
                }
                break;
            case 1:
                linearLayout_search.setVisibility(View.VISIBLE);
                break;
            case 2:
                finish();
                break;
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }

    String ReadTextFile(String strPath) {
        String path = strPath;
        String content = "";
        File file = new File(path);
        try {
            InputStream IS = new FileInputStream(file);
            if (IS != null) {
                InputStreamReader ISR = new InputStreamReader(IS);
                BufferedReader BR = new BufferedReader(ISR);
                String line;
                //分行读取
                while (( line = BR.readLine()) != null) {
                    content += line + "\n";
                }
                IS.close();
            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
        }
        return content;
    }

    class MyOnClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.imageButton_search_prev:
                    String s = editText.getText().toString();
                    String st = editText_search.getText().toString();
                    if (!s.equals("") && !st.equals("")) {
                        index = s.lastIndexOf(st, index - 1);
                        if (index == -1) {
                            index = 0;
                            imageButton_search_next.performClick();
                        } else {
                            textView_search_index.setText("" + index);
                            editText.setSelection(index);
                        }
                    }
                    break;
                case R.id.imageButton_search_next:
                    s = editText.getText().toString();
                    st = editText_search.getText().toString();
                    if (!s.equals("") && !st.equals("")) {
                        index = s.indexOf(st, index + 1);
                        if (index == -1) {
                            index = 0;
                            imageButton_search_next.performClick();
                        } else {
                            textView_search_index.setText("" + index);
                            editText.setSelection(index);
                        }
                    }
                    break;
                case R.id.imageButton_search_close:
                    linearLayout_search.setVisibility(View.GONE);
                    break;
            }
        }
    }

}
